package com.todod.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.todod.common.util.Doc2PdfUtil;
import com.todod.common.util.MinIoUtils;
import com.todod.common.util.ReadFile;
import com.todod.common.util.ReadFileTest;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.dto.EsBmwdDto;
import com.todod.dto.PublicFileDto;
import com.todod.entity.QueryPublicFile;
import com.todod.exception.UploadFileException;
import com.todod.mapper.CatalogDetailMapper;
import com.todod.mapper.CatalogManageMapper;
import com.todod.mapper.PublicCatalogMapper;
import com.todod.mapper.PublicFileAuthorityMapper;
import com.todod.mapper.PublicFileMapper;
import com.todod.model.CatalogDetail;
import com.todod.model.CatalogManage;
import com.todod.model.PublicCatalog;
import com.todod.model.PublicFile;
import com.todod.model.PublicFileAuthority;
import com.todod.model.PublicFileEvaluate;
import com.todod.model.PublicFileQuantity;
import com.todod.model.Role;
import com.todod.model.User;
import com.todod.model.UserRole;

/**
 * @param
 * @author dyl
 * @date 2021-03-16
 */
@Service
@Transactional
public class PublicFileService {

	@Value("${file.upload.path}")
	private String uploadPath;
	@Value("${file.upload.mapping}")
	private String showPath;
	@Value("${file.visit}")
	private String visi;
	@Autowired
	private PublicFileMapper publicFileMapper;
	@Autowired
	private IUserService iUserService;
	@Autowired
	public PublicFileEvaluateService publicFileEvaluateService;
	@Autowired
	private ElasticsearchService elasticsearchService;

	Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	public PublicFileEvaluateService projectFileEvaluateService;
	@Autowired
	public PublicCatalogService publicCatalogService;
	@Autowired
	private RestHighLevelClient restHighLevelClient;
	@Autowired
	public PublicCatalogMapper publicCatalogMapper;
	@Autowired
	public PublicFileQuantityService publicFileQuantityService;
	@Autowired
	private PublicFileAuthorityMapper fileAuthorityMapper;
	@Autowired
	private IRoleService iRoleService;
	@Autowired
	private IUserRoleService iUserRoleService;
	// 存储桶名称
	@Value("${minio.bucketName}")
	private String bucketName;
	@Autowired
	private MinIoUtils minIoUtils;
	@Autowired
	public ICatalogDetailService catalogDetailService;
	@Autowired
	public CatalogManageMapper catalogManageMapper;
	@Autowired
	public CatalogDetailMapper catalogDetailMapper;

	/**
	 * 
	 * @param _userId
	 * @param queryPublicFile
	 * @return
	 */
	public IPage<PublicFileDto> getListPage(Long _userId, QueryPublicFile queryPublicFile) {
		Page<PublicFileDto> page = new Page<>(queryPublicFile.getPage(), queryPublicFile.getLimit());

		IPage<PublicFileDto> iPage = null;
		if (queryPublicFile.getFlag().equalsIgnoreCase("M")) {
			iPage = publicFileMapper.getNewList1(page, _userId, queryPublicFile);
		} else {
			iPage = publicFileMapper.getNewList2(page, _userId, queryPublicFile);
		}

		List<User> userList = iUserService.getAllList();
		List<PublicFileDto> records = iPage.getRecords();
		for (PublicFileDto record : records) {
			Optional<User> any = userList.stream().filter((x) -> x.getId().equals(record.getCreateuserId())).findAny();

			if (any.isPresent()) {
				record.setCreateuserName(any.get().getNickName());

				if (!_userId.equals(any.get().getId())) {// 判断登录人与创建人是否一致
					record.setIsEdit("1");
					record.setShareFlag("0");
					List<PublicFileEvaluate> list = publicFileEvaluateService.getEvaluateListByFileId(record.getId());
					if (list != null && list.size() > 0) {
						record.setIsEdit("3");
					}
				} else {
					record.setShareFlag("1");
					record.setIsEdit("2");
				}
			}
			record.setUrl(visi + record.getRelativePath());

			if (!_userId.equals(record.getCreateuserId())) {// 判断登录人与创建人是否一致
				record.setShareFlag("0");
			} else {
				record.setShareFlag("1");
			}

			if (!record.getFileSize().equalsIgnoreCase("-")) {

				BigDecimal size = new BigDecimal(record.getFileSize());
				BigDecimal divide1 = new BigDecimal("1024");
				BigDecimal divide2 = new BigDecimal("1024").multiply(new BigDecimal("1024"));
				BigDecimal divide3 = new BigDecimal("1024")
						.multiply(new BigDecimal("1024").multiply(new BigDecimal("1024")));
				Double d1 = size.divide(divide1, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d2 = size.divide(divide2, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d3 = size.divide(divide3, 2, BigDecimal.ROUND_HALF_UP).doubleValue();

				if (d1 < 1) {
					record.setFileSize("1KB");
				} else if (d1 >= 1) {
					record.setFileSize(d1.toString() + "KB");
				}
				if (d2 >= 1) {
					record.setFileSize(d2.toString() + "MB");
				}
				if (d3 >= 1) {
					record.setFileSize(d3.toString() + "GB");
				}
			}
		}

		return iPage;
	}

	/**
	 * 
	 * @param _userId
	 * @param publicFile
	 * @throws Exception
	 */
	public void saveData(Long _userId, PublicFile publicFile) throws Exception {

		if (publicFile.getType().equalsIgnoreCase("M")) {
			// 父数据
			CatalogDetail catalogDetail = catalogDetailMapper.selectById(publicFile.getGftId());
			if (catalogDetail.getLevels() != null && StringUtils.isNotBlank(catalogDetail.getLevels())) {
				publicFile.setLevel(catalogDetail.getLevels() + catalogDetail.getId() + ";");
			} else {
				publicFile.setLevel(catalogDetail.getId() + ";");
			}
		} else {
			// 父数据
			PublicCatalog publicCatalogParent = publicCatalogMapper.selectById(publicFile.getGftId());
			if (publicCatalogParent.getLevels() != null && StringUtils.isNotBlank(publicCatalogParent.getLevels())) {
				publicFile.setLevel(publicCatalogParent.getLevels() + publicCatalogParent.getId() + ";");
			} else {
				publicFile.setLevel(publicCatalogParent.getId() + ";");
			}
		}

		publicFile.setState("1");
		publicFile.setCreateuserId(_userId);
		publicFile.setCreatetimeTi(LocalDateTime.now());

		try {
			insertDoc(publicFile, "save");
			publicFileMapper.insert(publicFile);

			if (publicFile.getType().equalsIgnoreCase("M")) {
				User user = iUserService.getById(_userId);
				List<Role> roleList = iRoleService.getByCompanyId(user.getDepartid());
				for (Role role : roleList) {
					List<UserRole> list = iUserRoleService.getByRoleId(role.getId());
					for (UserRole userRole : list) {
						PublicFileAuthority fileAuthority = new PublicFileAuthority();
						fileAuthority.setId(SnowflakeIdGenerator.getId());
						fileAuthority.setFileId(Long.valueOf(publicFile.getBatchCode()));
						fileAuthority.setUserId(userRole.getUserId());
						fileAuthority.setCreateuserId(_userId);
						fileAuthority.setCreatetimeTi(LocalDateTime.now());
						fileAuthorityMapper.insert(fileAuthority);
					}
				}
			}
		} catch (Exception e) {
			throw new Exception("上传文件失败，请稍后再试");
		}
	}

	/**
	 * 
	 * @param _userId
	 * @param publicFile
	 * @throws Exception
	 */
	public void editData(Long _userId, PublicFile publicFile) throws Exception {
		PublicFile publicFile1 = publicFileMapper.selectById(publicFile.getId());

		publicFile1.setState("2");
		publicFile1.setCreateuserId(publicFile1.getCreateuserId());
		publicFile1.setCreatetimeTi(publicFile1.getCreatetimeTi());
		publicFile1.setModifyuserId(_userId);
		publicFile1.setModifytimeTi(LocalDateTime.now());

		try {
			insertDoc(publicFile1, "edit");
			publicFileMapper.updateById(publicFile1);

			// 父数据
			PublicCatalog publicCatalogParent = publicCatalogMapper.selectById(publicFile.getGftId());
			if (publicCatalogParent.getLevels() != null && StringUtils.isNotBlank(publicCatalogParent.getLevels())) {
				publicFile.setLevel(publicCatalogParent.getLevels() + publicCatalogParent.getId() + ";");
			} else {
				publicFile.setLevel(publicCatalogParent.getId() + ";");
			}

			publicFile.setId(SnowflakeIdGenerator.getId());
			publicFile.setSortNum(publicFile1.getSortNum() + 1);
			publicFile.setState("1");
			publicFile.setBatchCode(publicFile1.getBatchCode());
			publicFile.setCreateuserId(_userId);
			publicFile.setCreatetimeTi(LocalDateTime.now());
			publicFileMapper.insert(publicFile);

			insertDoc(publicFile, "save");

			if (publicFile.getType().equalsIgnoreCase("M")) {
				User user = iUserService.getById(_userId);
				List<Role> roleList = iRoleService.getByCompanyId(user.getDepartid());
				for (Role role : roleList) {
					List<UserRole> list = iUserRoleService.getByRoleId(role.getId());
					for (UserRole userRole : list) {
						PublicFileAuthority fileAuthority = new PublicFileAuthority();
						fileAuthority.setId(SnowflakeIdGenerator.getId());
						fileAuthority.setFileId(Long.valueOf(publicFile.getBatchCode()));
						fileAuthority.setUserId(userRole.getUserId());
						fileAuthority.setCreateuserId(_userId);
						fileAuthority.setCreatetimeTi(LocalDateTime.now());
						fileAuthorityMapper.insert(fileAuthority);
					}
				}
			}
		} catch (Exception e) {
			throw new Exception("上传文件失败，请稍后再试");
		}
	}

	/**
	 * 文件下载
	 * 
	 * @param request
	 * @param response
	 * @param path
	 * @param fileName
	 * @throws IOException
	 * @throws Exception
	 */
	public void download(HttpServletRequest request, HttpServletResponse response, String path, String fileName)
			throws IOException {
		File file = new File(path);
		if (file.isFile()) {
			// 设置页面不缓存,清空buffer
			response.reset();
			response.setCharacterEncoding("UTF-8");// 字符编码
			// response.setContentType("application/octet-stream");
			response.setContentType("multipart/form-data");// 二进制传输数据
//				response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
			response.addHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
			// 设置信息给客户端不解析
			// String type = new MimetypesFileTypeMap().getContentType(fileName);
			String type = Files.probeContentType(Paths.get(path));
//				// 设置contenttype，即告诉客户端所发送的数据属于什么类型
			response.setHeader("Content-type", type);
			FileInputStream input = new FileInputStream(file);
			ServletOutputStream out = response.getOutputStream();
			byte[] buff = new byte[1024];
			int index = 0;
			while ((index = input.read(buff)) != -1) {
				out.write(buff, 0, index);
				out.flush();
			}
			out.close();
			input.close();
		}
	}

	/**
	 * 
	 * @param _userId
	 * @param queryPublicFile
	 * @return
	 */
	public IPage<PublicFileDto> getSPListPage(Long _userId, QueryPublicFile queryPublicFile) {
		Page<PublicFileDto> page = new Page<>(queryPublicFile.getPage(), queryPublicFile.getLimit());

		IPage<PublicFileDto> iPage = publicFileMapper.getSPListPage(page, _userId, queryPublicFile);

		List<PublicFileDto> records = iPage.getRecords();
		List<User> userList = iUserService.getAllList();
		for (PublicFileDto record : records) {

			Optional<User> any = userList.stream().filter((x) -> x.getId().equals(record.getCreateuserId())).findAny();
			if (any.isPresent()) {
				record.setCreateuserName(any.get().getNickName());
			}
		}

		return iPage;
	}

	/**
	 * 
	 * @param _userId
	 * @param request
	 * @param xftId
	 * @param companyId
	 * @param batchCode
	 * @return
	 */
	public PublicFile saveUploadFile(Long _userId, HttpServletRequest request, Long gftId, Long companyId,
			String batchCode) {

//		TrackerServer trackerServer = null;

		String relativePath = null, docPath = null, pdfPath = null, content = null;
		PublicFile publicFile = null;
		FileInputStream fis = null;
		try {

			MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
			MultipartFile uploadFile = req.getFile("uploadfile_ant");// 返回上传文件的内容和描述
			String originalName = uploadFile.getOriginalFilename();
			String file_ext_name = originalName.substring(originalName.lastIndexOf(".") + 1);
//			byte[] file_buff = uploadFile.getBytes();

//			trackerServer = trackerClient.getConnection();
//
//			StorageClient storageClient = new StorageClient(trackerServer, null);
//			// 文件上传参数1：需要上传文件的绝字节数组 参数2：上传文件的扩展名 参数3：文件的属性文件一般不上传
//			String[] result = storageClient.upload_file("knowledge", file_buff, file_ext_name, null);
//			String fileName = result[1].substring(result[1].lastIndexOf("/") + 1);
//			relativePath = "/" + result[0] + "/" + result[1];// 上传路径
//			String root = uploadPath;

			relativePath = minIoUtils.upload(uploadFile, bucketName, null);
//			abstractPath = minIoUtils.getObjectUrl(bucketName, relativePath, 7);

			int result01 = file_ext_name.indexOf("docx");
			int result02 = file_ext_name.indexOf("doc");
			int result03 = file_ext_name.indexOf("xlsx");
			int result04 = file_ext_name.indexOf("xls");
			int result05 = file_ext_name.indexOf("txt");
			int result06 = file_ext_name.indexOf("ppt");
			int result07 = file_ext_name.indexOf("pptx");
			int result08 = file_ext_name.indexOf("pdf");

			String path = ResourceUtils.getURL("classpath:").getPath() + File.separator + "static" + File.separator
					+ "file" + File.separator + "yulan";

			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}

			if (result01 != -1 || result02 != -1 || result05 != -1 || result06 != -1 || result07 != -1) {

				String pdfName = UUID.randomUUID().toString().replace("-", "") + ".pdf";

				docPath = path + File.separator + originalName;
				pdfPath = path + File.separator + pdfName;

				FileCopyUtils.copy(uploadFile.getInputStream(), new FileOutputStream(docPath));

				Doc2PdfUtil.word2Pdf(docPath, pdfPath);

				String surri = docPath.substring(docPath.lastIndexOf(".") + 1);

				if (surri.equalsIgnoreCase("doc")) {
					content = ReadFile.getContent2003(docPath);
				}
				if (surri.equalsIgnoreCase("docx")) {
					content = ReadFile.getContent2007(docPath);
				}
				if (surri.equalsIgnoreCase("ppt")) {
					content = ReadFile.readPPT(uploadFile);
				}
				if (surri.equalsIgnoreCase("pptx")) {
					content = ReadFile.readPPTX(uploadFile);
				}
				if (surri.equalsIgnoreCase("txt")) {
					content = ReadFile.readTxt(docPath);
				}
			}
			if (result08 != -1) {
				content = ReadFile.readPdf(uploadFile);
			}
			if (result03 != -1 || result04 != -1) {
				String pdfName = UUID.randomUUID().toString().replace("-", "") + ".pdf";

				docPath = path + File.separator + originalName;
				pdfPath = path + File.separator + pdfName;

				FileCopyUtils.copy(uploadFile.getInputStream(), new FileOutputStream(docPath));

				File file = new File(docPath);
				FileInputStream fileInputStream = new FileInputStream(file);

				if (file_ext_name.equalsIgnoreCase("xls")) {
					ReadFileTest.readExcelXls(docPath, pdfPath, fileInputStream, file_ext_name);
				} else if (file_ext_name.equalsIgnoreCase("xlsx")) {
					ReadFileTest.readExcelXlsx(docPath, pdfPath, fileInputStream, file_ext_name);
				}

				File file1 = new File(pdfPath);
				FileInputStream fileInputStream1 = new FileInputStream(file1);
				content = ReadFile.readPdf(fileInputStream1);
				fileInputStream1.close();
			}

			List<PublicFile> list = publicFileMapper.selectByGftId(gftId, batchCode);
//			if (result != null) {
			publicFile = new PublicFile();
			publicFile.setId(SnowflakeIdGenerator.getId());

			publicFile.setBatchCode(batchCode);
			publicFile.setDepartmentId(companyId);
			publicFile.setGftId(gftId);
			publicFile.setOriginalName(originalName);
			publicFile.setFileName(relativePath);
			publicFile.setSuffix(file_ext_name);
			publicFile.setFileSize(String.valueOf(uploadFile.getSize()));
			publicFile.setAbstractPath(visi + relativePath);
			publicFile.setRelativePath(relativePath);
			publicFile.setContent(content);

			if (pdfPath != null) {
//				String ext_name = pdfPath.substring(pdfPath.lastIndexOf(".") + 1);
				// 文件上传参数1：需要上传文件的绝字节数组 参数2：上传文件的扩展名 参数3：文件的属性文件一般不上传
				fis = new FileInputStream(pdfPath);

				File tofile1 = new File(pdfPath);

				String yulanPath = minIoUtils.newUpload(bucketName, tofile1.getName(), fis, "application/pdf", null);

				publicFile.setYulanPath(visi + yulanPath);
			}

			if (list.size() > 0) {
				publicFile.setSortNum(list.size() + 1);
			} else {
				publicFile.setSortNum(1);
			}

			publicFile.setCreateuserId(_userId);
			publicFile.setCreatetimeTi(LocalDateTime.now());
//			}

			if (pdfPath != null && StringUtils.isNotBlank(pdfPath)) {
				File tofile1 = new File(pdfPath);
				if (tofile1.exists()) {
					tofile1.delete();
				}
			}

			if (pdfPath != null && StringUtils.isNotBlank(pdfPath)) {
				File tofile = new File(docPath);

				if (tofile.exists()) {
					tofile.delete();
				}
			}

		} catch (Exception e) {
			log.error("file_upload", e);
			throw new UploadFileException("上传文件失败");
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		if (docPath != null) {
			File docFile = new File(docPath);
			File pdfFile = new File(pdfPath);
			docFile.delete();
			pdfFile.delete();
		}

		return publicFile;
	}

	/**
	 * 
	 * @param originalName
	 * @param gftId
	 * @return
	 */
	public boolean getFileByFileName(String originalName, Long gftId) {
		QueryWrapper<PublicFile> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("gf_original_name", originalName);
		queryWrapper.eq("gf_gft_id", gftId);
		queryWrapper.eq("gf_state", "1");

		List<PublicFile> list = publicFileMapper.selectList(queryWrapper);
		if (list.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

	public List<PublicFile> getFileByGftId(Long gftId) {
		QueryWrapper<PublicFile> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("gf_gft_id", gftId);
		queryWrapper.eq("gf_state", "1");

		List<PublicFile> list = publicFileMapper.selectList(queryWrapper);
		return list;
	}

	public void insertDoc(PublicFile publicFile, String flag) {

		String suffix = "png,jpeg,jpg,gif,tif,bmp,webp,ico,pdf,docx,doc,txt,ppt,pptx,xlsx,xls,mp4,mpeg,avi,navi,asf,mov,3gp,wmv,divx,xvid,rm,rmvb,flv,f4v,mp3,flac,wav,flac";

		EsBmwdDto bmwdDto = new EsBmwdDto();

		String gftName = "";
		if (publicFile.getType().equalsIgnoreCase("M")) {
			// 父数据
			CatalogDetail catalogDetail = catalogDetailMapper.selectById(publicFile.getGftId());
			gftName = catalogDetail.getTypeName() + gftName;

			if (catalogDetail.getParentId() != 1l && catalogDetail.getParentId() != null) {
				PublicCatalog a = new PublicCatalog();
				Long gftId = catalogDetail.getParentId();
				a.setId(gftId);
				QueryWrapper<CatalogManage> queryWrapper = new QueryWrapper<>();
				queryWrapper.eq("cm_code", "PUBLIC_CATALOG");
				queryWrapper.eq("cm_state", "1");

				CatalogManage catalogManage = catalogManageMapper.selectOne(queryWrapper);

				List<CatalogDetail> list = catalogDetailService.getTreeListInAuthority(catalogManage.getId());
				for (int i = 0; i < list.size(); i++) {
					if (a.getId() != 1l && a.getId() != null) {
						Optional<CatalogDetail> any = list.stream().filter((x) -> x.getId().equals(a.getId()))
								.findAny();
						if (any.isPresent()) {
							gftName = any.get().getTypeName() + "->" + gftName;
						}
					}
				}
			}
		} else {
			PublicCatalog publicCatalog = publicCatalogMapper.selectById(publicFile.getGftId());
			gftName = publicCatalog.getTypeName() + gftName;

			if (publicCatalog.getParentId() != 1l && publicCatalog.getParentId() != null) {
				PublicCatalog a = new PublicCatalog();
				Long gftId = publicCatalog.getParentId();
				a.setId(gftId);
				List<PublicCatalog> list = publicCatalogMapper.selectList(null);
				for (int i = 0; i < list.size(); i++) {
					if (a.getId() != 1l && a.getId() != null) {
						Optional<PublicCatalog> any = list.stream().filter((x) -> x.getId().equals(a.getId()))
								.findAny();
						if (any.isPresent()) {
							gftName = any.get().getTypeName() + "->" + gftName;
						}
					}
				}
			}
		}

		bmwdDto.setId(publicFile.getId());
		bmwdDto.setDepartmentId(publicFile.getDepartmentId());
		bmwdDto.setGftId(publicFile.getGftId());
		bmwdDto.setGftName(gftName);
		bmwdDto.setFileName(publicFile.getOriginalName());
		bmwdDto.setFileLabel(publicFile.getFileLabel());

		if (suffix.indexOf(publicFile.getSuffix()) < 0) {
			bmwdDto.setSuffix("其他");
		} else {
			bmwdDto.setSuffix(publicFile.getSuffix());
		}

		bmwdDto.setFileSize(publicFile.getFileSize());
		bmwdDto.setType(publicFile.getType());
		bmwdDto.setState(publicFile.getState());
		bmwdDto.setSortNum(publicFile.getSortNum());
		bmwdDto.setPaixu("paixu2");
		bmwdDto.setCreatetimeTi(publicFile.getCreatetimeTi().toString().replaceAll("T", " "));
		bmwdDto.setCreateuserId(publicFile.getCreateuserId());
		bmwdDto.setContent(publicFile.getContent());

		Integer downloads = 0, views = 0;
		List<PublicFileQuantity> list = publicFileQuantityService.getEvaluateListByFileId(bmwdDto.getId());
		for (PublicFileQuantity publicFileQuantity : list) {
			downloads = downloads + publicFileQuantity.getDownloads();
			views = views + publicFileQuantity.getViews();
		}
		bmwdDto.setDownloads(downloads);
		bmwdDto.setViews(views);

		User user = iUserService.getById(publicFile.getCreateuserId());
		bmwdDto.setUserName(user.getNickName());

		int result01 = bmwdDto.getSuffix().indexOf("docx");
		int result02 = bmwdDto.getSuffix().indexOf("doc");
		int result03 = bmwdDto.getSuffix().indexOf("xlsx");
		int result04 = bmwdDto.getSuffix().indexOf("xls");
		int result05 = bmwdDto.getSuffix().indexOf("txt");
		int result06 = bmwdDto.getSuffix().indexOf("ppt");
		int result07 = bmwdDto.getSuffix().indexOf("pptx");

		if (result01 != -1 || result02 != -1 || result03 != -1 || result04 != -1 || result05 != -1 || result06 != -1
				|| result07 != -1) {
			bmwdDto.setUrl(publicFile.getYulanPath());
		} else {
			bmwdDto.setUrl(publicFile.getAbstractPath());
		}

		try {
			if (flag.equalsIgnoreCase("save")) {
				BulkRequest bulkRequest = new BulkRequest();
				if (bmwdDto.getType().equalsIgnoreCase("M")) {
					bulkRequest.add(new IndexRequest("bmwd").id(String.valueOf(bmwdDto.getId()))
							.source(JSON.toJSONString(bmwdDto), XContentType.JSON));
				} else {
					bulkRequest.add(new IndexRequest("grwd").id(String.valueOf(bmwdDto.getId()))
							.source(JSON.toJSONString(bmwdDto), XContentType.JSON));
				}

				try {
					BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
					if (bulkResponse.hasFailures()) {
						System.out.println(bulkResponse.buildFailureMessage());
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				if (bmwdDto.getType().equalsIgnoreCase("M")) {
					elasticsearchService.updateDocs("bmwd", "_doc", String.valueOf(bmwdDto.getId()),
							(JSONObject) JSONObject.toJSON(bmwdDto));
				} else {
					elasticsearchService.updateDocs("grwd", "_doc", String.valueOf(bmwdDto.getId()),
							(JSONObject) JSONObject.toJSON(bmwdDto));
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e);
		}
	}

	/**
	 * @Title: copyData
	 * @Description:复制文件数据
	 * @author: wgb
	 * @date 2020-06-26
	 * @param _userId
	 * @param PublicFile
	 * @return
	 * @throws Exception
	 */
	public void copyData(Long _userId, PublicFile publicFile) throws Exception {

		PublicFile publicFileNew = publicFileMapper.selectById(publicFile.getId());

		publicFileNew.setId(SnowflakeIdGenerator.getId());
		publicFileNew.setBatchCode(SnowflakeIdGenerator.getId().toString());
		publicFileNew.setGftId(publicFile.getGftId());
		publicFileNew.setDepartmentId(publicFile.getDepartmentId());
		publicFileNew.setCreateuserId(_userId);
		publicFileNew.setCreatetimeTi(LocalDateTime.now());
		publicFileNew.setModifyuserId(_userId);
		publicFileNew.setModifytimeTi(LocalDateTime.now());

		if (publicFileNew.getGftId() != 1) {
			// 父数据
			PublicCatalog publicCatalogParent = publicCatalogMapper.selectById(publicFile.getGftId());
			if (publicCatalogParent.getLevels() != null) {
				publicFileNew.setLevel(publicCatalogParent.getLevels() + publicCatalogParent.getId() + ";");
			}
		}

		try {
			insertDoc(publicFileNew, "save");
			publicFileMapper.insert(publicFileNew);

			if (publicFileNew.getType().equalsIgnoreCase("M")) {
				PublicFileAuthority fileAuthority = new PublicFileAuthority();
				fileAuthority.setId(SnowflakeIdGenerator.getId());
				fileAuthority.setFileId(Long.valueOf(publicFileNew.getBatchCode()));
				fileAuthority.setUserId(_userId);
				fileAuthority.setCreateuserId(_userId);
				fileAuthority.setCreatetimeTi(LocalDateTime.now());
				fileAuthorityMapper.insert(fileAuthority);
			}
		} catch (Exception e) {
			throw new Exception("上传文件失败，请稍后再试");
		}
	}

	/**
	 * @Title: moveData
	 * @Description:移动文件数据
	 * @author: wgb
	 * @date 2020-06-26
	 * @param _userId
	 * @param PublicFile
	 * @return
	 * @throws Exception
	 */
	public void moveData(Long _userId, PublicFile publicFile) throws Exception {
		PublicFile publicFileNew = publicFileMapper.selectById(publicFile.getId());

		publicFileNew.setGftId(publicFile.getGftId());
		publicFileNew.setDepartmentId(publicFile.getDepartmentId());
		publicFileNew.setModifyuserId(_userId);
		publicFileNew.setModifytimeTi(LocalDateTime.now());
		if (publicFileNew.getGftId() != 1) {
			// 父数据
			PublicCatalog publicCatalogParent = publicCatalogMapper.selectById(publicFile.getGftId());
			if (publicCatalogParent.getLevels() != null) {
				publicFileNew.setLevel(publicCatalogParent.getLevels() + publicCatalogParent.getId() + ";");
			} else {
				publicFileNew.setLevel(publicCatalogParent.getId() + ";");
			}
		}

		try {
			insertDoc(publicFileNew, "edit");
			publicFileMapper.updateById(publicFileNew);
		} catch (Exception e) {
			throw new Exception("上传文件失败，请稍后再试");
		}
	}

	/**
	 * @Title: getListFileByParentId
	 * @Description:根据目录id获取子文件
	 * @author: wgb
	 * @date 2020-06-26
	 * @param _userId
	 * @param gftId
	 * @return List<PublicFile>
	 */
	public List<PublicFile> getListFileByParentId(Long gftId) {
		QueryWrapper<PublicFile> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("gf_gft_id", gftId);
		queryWrapper.orderByAsc("gf_sort_num");
		return publicFileMapper.selectList(queryWrapper);
	}

	public int getSortByDate(String format) {
		QueryWrapper<PublicFile> queryWrapper = new QueryWrapper<>();
		queryWrapper.like("DATE_FORMAT(gf_createtime_ti,'%Y-%m-%d')", format);
		queryWrapper.eq("gf_state", "1");
		return publicFileMapper.selectList(queryWrapper).size();
	}

	/**
	 * @Title: getListPageInState
	 * @Description:根据查询条件和用户id获取文件夹及文件（文件名、状态、用户id）
	 * @author: wgb
	 * @date 2020-06-28
	 * @param _userId
	 * @param QueryPublicFile
	 * @return IPage<PublicFileDto>
	 */
	public IPage<PublicFileDto> getListPageInState(Long _userId, QueryPublicFile queryPublicFile) {
		Page<PublicFileDto> page = new Page<>(queryPublicFile.getPage(), queryPublicFile.getLimit());
		IPage<PublicFileDto> iPage = publicFileMapper.getListPageInState(page, _userId, queryPublicFile);
		List<PublicFileDto> records = iPage.getRecords();
		for (PublicFileDto record : records) {
			if (!record.getFileSize().equalsIgnoreCase("-")) {
				BigDecimal size = new BigDecimal(record.getFileSize());
				BigDecimal divide1 = new BigDecimal("1024");
				BigDecimal divide2 = new BigDecimal("1024").multiply(new BigDecimal("1024"));
				BigDecimal divide3 = new BigDecimal("1024")
						.multiply(new BigDecimal("1024").multiply(new BigDecimal("1024")));
				Double d1 = size.divide(divide1, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d2 = size.divide(divide2, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d3 = size.divide(divide3, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				if (d1 < 1) {
					record.setFileSize("1KB");
				} else if (d1 >= 1) {
					record.setFileSize(d1.toString() + "KB");
				}
				if (d2 >= 1) {
					record.setFileSize(d2.toString() + "MB");
				}
				if (d3 >= 1) {
					record.setFileSize(d3.toString() + "GB");
				}
			}
		}
		return iPage;
	}

	/**
	 * @Title: deleteById
	 * @Description:根据Id删除file
	 * @author: wgb
	 * @date 2020-06-28
	 * @param id
	 * @return
	 */
	public void deleteById(Long id) {
		publicFileMapper.deleteById(id);
	}

	/**
	 * @Title: updateUserAndStatus
	 * @Description:更新用户和状态
	 * @author: wgb
	 * @date 2020-06-26
	 * @param _userId
	 * @param id
	 * @param status
	 * @return
	 * @throws Exception
	 */
	public void updateUserAndStatus(Long _userId, Long id, String status) throws Exception {
		PublicFile publicFileNew = publicFileMapper.selectById(id);
		if (publicFileNew != null) {
			publicFileNew.setState(status);
			publicFileNew.setModifyuserId(_userId);
			publicFileNew.setModifytimeTi(LocalDateTime.now());

			publicFileMapper.updateById(publicFileNew);

			try {
				insertDoc(publicFileNew, "edit");
			} catch (Exception e) {
				throw new Exception("文件修改失败，请稍后再试");
			}
		}
	}

	/**
	 * @Title: selectByCodeInUse
	 * @Description:根据批次号获取正在使用的文件
	 * @author: wgb
	 * @date 2020-06-28
	 * @param id
	 * @return PublicFile
	 */
	public PublicFile selectByCodeInUse(Long code) {
		QueryWrapper<PublicFile> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("gf_batch_code", code);
		queryWrapper.eq("gf_state", "1");
		return publicFileMapper.selectOne(queryWrapper);
	}

	/**
	 * @Title: getShareListPage
	 * @Description: 获取共享文件夹下内容
	 * @author wgb
	 * @date 2021年6月30日
	 * @param _userId
	 * @param QueryPublicFile
	 * @return IPage<PublicFileDto>
	 */
	public IPage<PublicFileDto> getShareListPage(Long _userId, QueryPublicFile queryPublicFile) {
		Page<PublicFileDto> page = new Page<>(queryPublicFile.getPage(), queryPublicFile.getLimit());
		IPage<PublicFileDto> iPage = null;

		// 共享文档
		if (queryPublicFile.getType().equalsIgnoreCase("2")) {// 根节点
			iPage = publicFileMapper.getShareRootList(page, _userId, queryPublicFile);
		} else {// 子页面
			iPage = publicFileMapper.getShareList(page, _userId, queryPublicFile);
		}

		List<PublicFileDto> records = iPage.getRecords();
		for (PublicFileDto record : records) {
			User user = iUserService.getById(record.getCreateuserId());
			record.setCreateuserName(user.getNickName());
			record.setIsEdit("3");
			record.setUrl(visi + record.getRelativePath());

			if (!record.getFileSize().equalsIgnoreCase("-")) {

				BigDecimal size = new BigDecimal(record.getFileSize());
				BigDecimal divide1 = new BigDecimal("1024");
				BigDecimal divide2 = new BigDecimal("1024").multiply(new BigDecimal("1024"));
				BigDecimal divide3 = new BigDecimal("1024")
						.multiply(new BigDecimal("1024").multiply(new BigDecimal("1024")));
				Double d1 = size.divide(divide1, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d2 = size.divide(divide2, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d3 = size.divide(divide3, 2, BigDecimal.ROUND_HALF_UP).doubleValue();

				if (d1 < 1) {
					record.setFileSize("1KB");
				} else if (d1 >= 1) {
					record.setFileSize(d1.toString() + "KB");
				}
				if (d2 >= 1) {
					record.setFileSize(d2.toString() + "MB");
				}
				if (d3 >= 1) {
					record.setFileSize(d3.toString() + "GB");
				}
			}
		}

		return iPage;
	}

	/**
	 * @title 获取我的文档第二层目录列表
	 * @param _userId
	 * @param queryPublicFile
	 * @return
	 */
	public IPage<PublicFileDto> getFileShareList(Long _userId, QueryPublicFile queryPublicFile) {
		Page<PublicFileDto> page = new Page<>(queryPublicFile.getPage(), queryPublicFile.getLimit());

		IPage<PublicFileDto> iPage = publicFileMapper.getFileShareSecond(page, _userId, queryPublicFile);

		List<User> userList = iUserService.getAllList();
		List<PublicFileDto> records = iPage.getRecords();
		for (PublicFileDto record : records) {
			Optional<User> any = userList.stream().filter((x) -> x.getId().equals(record.getCreateuserId())).findAny();

			if (any.isPresent()) {
				record.setCreateuserName(any.get().getNickName());

				if (!_userId.equals(any.get().getId())) {// 判断登录人与创建人是否一致
					record.setIsEdit("1");
					List<PublicFileEvaluate> list = publicFileEvaluateService.getEvaluateListByFileId(record.getId());
					if (list != null && list.size() > 0) {
						record.setIsEdit("3");
					}
				} else {
					record.setIsEdit("2");
				}
			}
			record.setUrl(visi + record.getRelativePath());

			if (!record.getFileSize().equalsIgnoreCase("-")) {

				BigDecimal size = new BigDecimal(record.getFileSize());
				BigDecimal divide1 = new BigDecimal("1024");
				BigDecimal divide2 = new BigDecimal("1024").multiply(new BigDecimal("1024"));
				BigDecimal divide3 = new BigDecimal("1024")
						.multiply(new BigDecimal("1024").multiply(new BigDecimal("1024")));
				Double d1 = size.divide(divide1, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d2 = size.divide(divide2, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d3 = size.divide(divide3, 2, BigDecimal.ROUND_HALF_UP).doubleValue();

				if (d1 < 1) {
					record.setFileSize("1KB");
				} else if (d1 >= 1) {
					record.setFileSize(d1.toString() + "KB");
				}
				if (d2 >= 1) {
					record.setFileSize(d2.toString() + "MB");
				}
				if (d3 >= 1) {
					record.setFileSize(d3.toString() + "GB");
				}
			}
		}

		return iPage;
	}

	/**
	 * 
	 * @param _userId
	 * @param queryPublicFile
	 * @return
	 */
	public IPage<PublicFileDto> getFileSharePage(Long _userId, QueryPublicFile queryPublicFile) {
		Page<PublicFileDto> page = new Page<>(queryPublicFile.getPage(), queryPublicFile.getLimit());

		IPage<PublicFileDto> iPage = publicFileMapper.getFileSharePage(page, _userId, queryPublicFile);

		List<User> userList = iUserService.getAllList();
		List<PublicFileDto> records = iPage.getRecords();
		for (PublicFileDto record : records) {
			Optional<User> any = userList.stream().filter((x) -> x.getId().equals(record.getCreateuserId())).findAny();

			if (any.isPresent()) {
				record.setCreateuserName(any.get().getNickName());

				if (!_userId.equals(any.get().getId())) {// 判断登录人与创建人是否一致
					record.setIsEdit("1");
					List<PublicFileEvaluate> list = publicFileEvaluateService.getEvaluateListByFileId(record.getId());
					if (list != null && list.size() > 0) {
						record.setIsEdit("3");
					}
				} else {
					record.setIsEdit("2");
				}
			}
			record.setUrl(visi + record.getRelativePath());

			if (!record.getFileSize().equalsIgnoreCase("-")) {

				BigDecimal size = new BigDecimal(record.getFileSize());
				BigDecimal divide1 = new BigDecimal("1024");
				BigDecimal divide2 = new BigDecimal("1024").multiply(new BigDecimal("1024"));
				BigDecimal divide3 = new BigDecimal("1024")
						.multiply(new BigDecimal("1024").multiply(new BigDecimal("1024")));
				Double d1 = size.divide(divide1, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d2 = size.divide(divide2, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d3 = size.divide(divide3, 2, BigDecimal.ROUND_HALF_UP).doubleValue();

				if (d1 < 1) {
					record.setFileSize("1KB");
				} else if (d1 >= 1) {
					record.setFileSize(d1.toString() + "KB");
				}
				if (d2 >= 1) {
					record.setFileSize(d2.toString() + "MB");
				}
				if (d3 >= 1) {
					record.setFileSize(d3.toString() + "GB");
				}
			}
		}

		return iPage;
	}

	/**
	 * 
	 * @param departId
	 * @return
	 */
	public List<PublicFile> getFiles(Long departId) {
		QueryWrapper<PublicFile> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("gf_department_id", departId);
//		queryWrapper.eq("gf_state", "1");

		List<PublicFile> list = publicFileMapper.selectList(queryWrapper);
		return list;
	}

	public IPage<PublicFileDto> getCollectListPage(Long _userId, QueryPublicFile queryPublicFile) {

		Page<PublicFileDto> page = new Page<>(queryPublicFile.getPage(), queryPublicFile.getLimit());
		IPage<PublicFileDto> iPage = publicFileMapper.getCollectList(page, _userId, queryPublicFile);

		List<PublicFileDto> records = iPage.getRecords();
		for (PublicFileDto record : records) {
			User user = iUserService.getById(record.getCreateuserId());
			record.setCreateuserName(user.getNickName());
			record.setIsEdit("3");
			record.setUrl(visi + record.getRelativePath());

			if (!record.getFileSize().equalsIgnoreCase("-")) {

				BigDecimal size = new BigDecimal(record.getFileSize());
				BigDecimal divide1 = new BigDecimal("1024");
				BigDecimal divide2 = new BigDecimal("1024").multiply(new BigDecimal("1024"));
				BigDecimal divide3 = new BigDecimal("1024")
						.multiply(new BigDecimal("1024").multiply(new BigDecimal("1024")));
				Double d1 = size.divide(divide1, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d2 = size.divide(divide2, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d3 = size.divide(divide3, 2, BigDecimal.ROUND_HALF_UP).doubleValue();

				if (d1 < 1) {
					record.setFileSize("1KB");
				} else if (d1 >= 1) {
					record.setFileSize(d1.toString() + "KB");
				}
				if (d2 >= 1) {
					record.setFileSize(d2.toString() + "MB");
				}
				if (d3 >= 1) {
					record.setFileSize(d3.toString() + "GB");
				}
			}
		}

		return iPage;
	}

	public void batchSave(Long _userId, PublicFile publicFile1, List<PublicFile> list) throws Exception {

		for (PublicFile publicFile : list) {

			if (publicFile1.getType().equalsIgnoreCase("M")) {
				// 父数据
				CatalogDetail catalogDetail = catalogDetailMapper.selectById(publicFile.getGftId());
				if (catalogDetail.getLevels() != null && StringUtils.isNotBlank(catalogDetail.getLevels())) {
					publicFile.setLevel(catalogDetail.getLevels() + catalogDetail.getId() + ";");
				} else {
					publicFile.setLevel(catalogDetail.getId() + ";");
				}
			} else {
				// 父数据
				PublicCatalog publicCatalogParent = publicCatalogMapper.selectById(publicFile.getGftId());
				if (publicCatalogParent.getLevels() != null
						&& StringUtils.isNotBlank(publicCatalogParent.getLevels())) {
					publicFile.setLevel(publicCatalogParent.getLevels() + publicCatalogParent.getId() + ";");
				} else {
					publicFile.setLevel(publicCatalogParent.getId() + ";");
				}
			}

			publicFile.setBatchCode(SnowflakeIdGenerator.getId().toString());
			publicFile.setType(publicFile1.getType());
			publicFile.setApprovelState("2");
			publicFile.setState("1");
			publicFile.setCreateuserId(_userId);
			publicFile.setCreatetimeTi(LocalDateTime.now());

			try {
				insertDoc(publicFile, "save");

				publicFileMapper.insert(publicFile);

				if (publicFile.getType().equalsIgnoreCase("M")) {
					User user = iUserService.getById(_userId);
					List<Role> roleList = iRoleService.getByCompanyId(user.getDepartid());
					for (Role role : roleList) {
						List<UserRole> list1 = iUserRoleService.getByRoleId(role.getId());
						for (UserRole userRole : list1) {
							PublicFileAuthority fileAuthority = new PublicFileAuthority();
							fileAuthority.setId(SnowflakeIdGenerator.getId());
							fileAuthority.setFileId(Long.valueOf(publicFile.getBatchCode()));
							fileAuthority.setUserId(userRole.getUserId());
							fileAuthority.setCreateuserId(_userId);
							fileAuthority.setCreatetimeTi(LocalDateTime.now());
							fileAuthorityMapper.insert(fileAuthority);
						}
					}
				}
			} catch (Exception e) {
				throw new Exception("上传文件失败，请稍后再试");
			}
		}
	}

	public IPage<PublicFileDto> getNewListPage(Long _userId, QueryPublicFile queryPublicFile) {
		Page<PublicFileDto> page = new Page<>(queryPublicFile.getPage(), queryPublicFile.getLimit());

		IPage<PublicFileDto> iPage = publicFileMapper.getNewListPage(page, _userId, queryPublicFile);

		List<User> userList = iUserService.getAllList();
		List<PublicFileDto> records = iPage.getRecords();
		for (PublicFileDto record : records) {
			Optional<User> any = userList.stream().filter((x) -> x.getId().equals(record.getCreateuserId())).findAny();

			if (any.isPresent()) {
				record.setCreateuserName(any.get().getNickName());

				if (!_userId.equals(any.get().getId())) {// 判断登录人与创建人是否一致
					record.setIsEdit("1");
					record.setShareFlag("0");
					List<PublicFileEvaluate> list = publicFileEvaluateService.getEvaluateListByFileId(record.getId());
					if (list != null && list.size() > 0) {
						record.setIsEdit("3");
					}
				} else {
					record.setShareFlag("1");
					record.setIsEdit("2");
				}
			}
			record.setUrl(visi + record.getRelativePath());

			if (!_userId.equals(record.getCreateuserId())) {// 判断登录人与创建人是否一致
				record.setShareFlag("0");
			} else {
				record.setShareFlag("1");
			}

			if (!record.getFileSize().equalsIgnoreCase("-")) {

				BigDecimal size = new BigDecimal(record.getFileSize());
				BigDecimal divide1 = new BigDecimal("1024");
				BigDecimal divide2 = new BigDecimal("1024").multiply(new BigDecimal("1024"));
				BigDecimal divide3 = new BigDecimal("1024")
						.multiply(new BigDecimal("1024").multiply(new BigDecimal("1024")));
				Double d1 = size.divide(divide1, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d2 = size.divide(divide2, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double d3 = size.divide(divide3, 2, BigDecimal.ROUND_HALF_UP).doubleValue();

				if (d1 < 1) {
					record.setFileSize("1KB");
				} else if (d1 >= 1) {
					record.setFileSize(d1.toString() + "KB");
				}
				if (d2 >= 1) {
					record.setFileSize(d2.toString() + "MB");
				}
				if (d3 >= 1) {
					record.setFileSize(d3.toString() + "GB");
				}
			}
		}

		return iPage;
	}

}
